package mspbots.cw.business.core.boards;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.business.core.BaseReceiver;
import mspbots.cw.common.ResultMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * @author Jay.Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class BoardAssociationsReceiver extends BaseReceiver {

    private final BoardAssociationsRepository boardAssociationsRepository;

    @RabbitListener(queues = "connect-wise.boards.associations.tl")
    public void process(ResultMsg resultMsg) {
        JsonNode entity = resultMsg.getEntity();
        BoardAssociations data = BoardAssociations.builder()
                .cwId(resultMsg.getId())
                .boardId(super.getLongValueId(entity.get("board")))
                .boardName(super.getStringValueName(entity.get("board")))
                .itemId(super.getLongValueId(entity.get("item")))
                .itemName(super.getStringValueName(entity.get("item")))
                .subTypeId(super.getLongValueId(entity.get("subType")))
                .subTypeName(super.getStringValueName(entity.get("subType")))
                .typeId(super.getLongValueId(entity.get("type")))
                .typeName(super.getStringValueName(entity.get("type")))
                .syncTime(resultMsg.getSyncDate())
                .build();
        data.setTenantCode(resultMsg.getTenantId());

        this.boardAssociationsRepository.findByCwIdAndTenantCode(resultMsg.getId(), resultMsg.getTenantId())
                .map(result -> {
                    data.setId(result.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.boardAssociationsRepository::save).block(Duration.ofSeconds(10));
    }

}
